<template>
  <CommonPage show-footer title="功能检测">
    <NCard>
      <NForm
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="left"
        :label-width="100"
        style="max-width: 600px"
      >
        <NFormItem label="旋翼类型" path="rotor_type_id">
          <NSelect
            v-model:value="formData.rotor_type_id"
            :options="rotorTypeOptions"
            placeholder="请选择旋翼类型"
            style="width: 240px"
          />
        </NFormItem>
        
        <NFormItem label="检测项目" path="detection_type">
          <NRadioGroup v-model:value="formData.detection_type">
            <div class="mb-2">
              <NRadio :value="0">平稳性检测</NRadio>
            </div>
            <div>
              姿态检测：
              <NRadio :value="1">俯仰</NRadio>
              <NRadio :value="2">偏航</NRadio>
              <NRadio :value="3">横滚</NRadio>
            </div>
          </NRadioGroup>
        </NFormItem>

        <NSpace>
          <NButton 
            type="primary"
            :disabled="!formData.rotor_type_id || formData.detection_type === null || detecting"
            @click="startDetection"
          >
            开始检测
          </NButton>
          
          <NButton 
            type="error"
            :disabled="!detecting"
            @click="stopDetection"
          >
            停止检测
          </NButton>
        </NSpace>
      </NForm>

      <div v-if="detecting" class="mt-4">
        <NH2>实时检测数据</NH2>
        
        <NGrid :cols="2" :x-gap="12">
          <NGi>
            <NCard title="旋翼数据" class="mb-4">
              <NTable :single-line="false" :bordered="false">
                <thead>
                  <tr>
                    <th>旋翼</th>
                    <th>方向</th>
                    <th>转速</th>
                    <th>波动</th>
                    <th>姿态角</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(rotor, index) in detectionData.rotors" :key="index">
                    <td>{{ index + 1 }}号</td>
                    <td>{{ rotor.direction }}</td>
                    <td>{{ rotor.speed }}rpm</td>
                    <td>{{ rotor.fluctuation }}%</td>
                    <td>{{ rotor.attitude_angle }}°</td>
                  </tr>
                </tbody>
              </NTable>
            </NCard>

            <NCard title="检测结果">
              <NH3>{{ detectionData.detection_result }}</NH3>
            </NCard>
          </NGi>

          <NGi>
            <NCard title="姿态动画">
              <div class="animation-container">
                <img 
                  v-if="detectionData.result_code"
                  :src="`/resource/static/animations/${detectionData.result_code}.gif`"
                  :alt="detectionData.detection_result"
                  class="uav-image"
                  @error="handleImageError"
                />
              </div>
            </NCard>
          </NGi>
        </NGrid>
      </div>
    </NCard>
  </CommonPage>
</template>

<script setup>
import { ref, onBeforeUnmount, onMounted } from 'vue'
import { NButton, NForm, NFormItem, NSelect, NRadioGroup, NRadio, NSpace, NCard, NGrid, NGi, NTable, NH2, NH3 } from 'naive-ui'
import api from '@/api/detection'
import rotorApi from '@/api/rotor'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { getToken } from '@/utils'
import { useRouter, onBeforeRouteLeave } from 'vue-router'

const formRef = ref(null)
const formData = ref({
  rotor_type_id: 4,
  detection_type: null
})

const detecting = ref(false)
const detectionId = ref(null)
const eventSource = ref(null)

const rotorTypeOptions = ref([])
const detectionData = ref({
  rotors: [],
  detection_result: '',
  result_code: null
})

const rules = {
  rotor_type_id: {
    required: true,
    type: 'number',
    message: '请选择旋翼类型',
    trigger: ['blur', 'change']
  },
  detection_type: {
    required: true,
    type: 'number',
    message: '请选择检测项目',
    trigger: ['blur', 'change']
  }
}

// 获取旋翼类型列表
async function getRotorTypes() {
  try {
    const res = await rotorApi.getRotorTypeList()
    let types = res.data.map(item => ({
      label: item.name,
      value: item.id
    }))
    
    // 如果列表为空或不包含四旋翼，添加默认的四旋翼类型
    if (types.length === 0 || !types.some(t => t.value === 4)) {
      types = [{
        label: '四旋翼',
        value: 4
      }]
    }
    
    rotorTypeOptions.value = types
    formData.value.rotor_type_id = 4
    
  } catch (error) {
    window.$message.error('获取旋翼类型列表失败')
    rotorTypeOptions.value = [{
      label: '四旋翼',
      value: 4
    }]
    formData.value.rotor_type_id = 4
  }
}

// 开始检测
async function startDetection() {
  try {
    await formRef.value?.validate()
    
    const res = await api.startDetection(formData.value)
    detectionId.value = res.data.detection_id
    detecting.value = true
    
    eventSource.value = new EventSourcePolyfill('http://127.0.0.1:9999/api/v1/detection/stream', {
      headers: { 'token': getToken() }
    })
    
    eventSource.value.onmessage = (event) => {
      try {
        detectionData.value = JSON.parse(event.data)
      } catch (err) {
        console.error('Failed to parse SSE data:', err)
      }
    }
    
    eventSource.value.onerror = () => {
      window.$message.error('检测数据流连接断开')
      detecting.value = false
      eventSource.value?.close()
      eventSource.value = null
    }
    
  } catch (error) {
    window.$message.error('开始检测失败')
  }
}

// 停止检测
async function stopDetection() {
  try {
    if (!detectionId.value) {
      console.error('No detection ID found')
      return
    }
    
    console.log('Stopping detection with ID:', detectionId.value)
    
    detecting.value = false
    if (eventSource.value) {
      try {
        eventSource.value.close()
      } catch (error) {
        console.error('Error closing event source:', error)
      }
      eventSource.value = null
    }
    
    detectionData.value = {
      rotors: [],
      detection_result: '',
      result_code: null
    }
    
    try {
      await api.stopDetection(detectionId.value)
      window.$message.success('检测已停止')
    } catch (error) {
      console.error('Stop API error:', error)
      window.$message.error('停止检测失败，但已清理前端状态')
    } finally {
      detectionId.value = null
    }
      
  } catch (error) {
    console.error('Stop detection error:', error)
    window.$message.error('停止检测失败')
    detecting.value = false
    eventSource.value = null
    detectionId.value = null
  }
}

// 导航守卫
onBeforeRouteLeave((to, from, next) => {
  if (detecting.value) {
    window.$dialog.warning({
      title: '提示',
      content: '检测任务正在进行中,是否停止检测并离开?',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        try {
          await stopDetection()
          next()
        } catch (error) {
          console.error('Error stopping detection:', error)
          next()
        }
      },
      onNegativeClick: () => {
        next(false)
      }
    })
  } else {
    next()
  }
})

// 组件卸载处理
onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', handleBeforeUnload)
  if (detecting.value) {
    stopDetection().catch(error => {
      console.error('Error stopping detection during unmount:', error)
    })
  }
})

// beforeunload 处理函数
const handleBeforeUnload = (e) => {
  if (detecting.value) {
    e.preventDefault()
    e.returnValue = ''
  }
}

// 页面加载时的事件监听
onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload)
  getRotorTypes()
})
</script>

<style scoped>
.animation-container {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.uav-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style> 